package com.ruoyi.util;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectResult;
import com.ruoyi.web.core.config.CosConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Base64;
import java.util.Random;

/**
 * TODO
 *
 * @author chenchuan2
 * @date 2023-01-13 14:19:48
 */
@Component
@Slf4j
public class CosClientUtil {

    @Autowired
    private COSClient cosClient;

    @Autowired
    private CosConfig cosConfig;

    /**
     * 获取远程http地址视图片
     *
     * @param strUrl
     * @return
     */
    public static byte[] getImageFromNetByUrl(String strUrl) {
        try {
            URL url = new URL(strUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5 * 1000);
            InputStream inStream = conn.getInputStream();
            byte[] btData = readInputStream(inStream);
            return btData;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 读取流
     *
     * @param inStream
     * @return
     * @throws Exception
     */
    public static byte[] readInputStream(InputStream inStream) throws Exception {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inStream.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }
        inStream.close();
        return outStream.toByteArray();
    }

    public String downloadUsingStream(String urlStr) throws IOException {
        String fileName = FileUtil.getFileName(urlStr);

        byte[] bytes = getImageFromNetByUrl(urlStr);

        ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);

        return uploadImgToCos(inputStream, fileName);
    }

    private static byte[] base64Decode2Bytes(String base64) {
        return Base64.getDecoder().decode(base64);
    }

    public String uploadImgToCos(String base64, String fileName) throws IOException {
        fileName = FileUtil.getFileName(fileName);
        //将字符串转换为byte数组
        int firstComma = base64.indexOf(",");
        if(firstComma >= 0) {
            base64 = base64.substring(firstComma + 1);
        }
        byte[] bytes = base64Decode2Bytes(base64.trim());

        //转化为输入流
        ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);

        return uploadImgToCos(inputStream, fileName);
    }

    /**
     * 以文件流方式上传图片
     *
     * @param is
     * @return
     * @throws Exception
     */
    public String uploadImgToCos(InputStream is, String fileName) {

        //图片名称
        Random random = new Random();
        //生成新的图片名称(随机数0-9999+系统当前时间+上传图片名)
        String name = random.nextInt(10000) + System.currentTimeMillis() + fileName;
        this.uploadFileToCos(is, name);
        return "https://" + cosConfig.getBucketName() + ".cos." + cosConfig.getRegion() + ".myqcloud.com/" + name;
    }

    /**
     * 上传到COS服务器 如果同名文件会覆盖服务器上的
     *
     * @param instream
     * @param key
     * @return 出错返回"" ,唯一MD5数字签名
     */
    public String uploadFileToCos(InputStream instream, String key) {
        String etag = "";
        try {
            // 创建上传Object的Metadata
            ObjectMetadata objectMetadata = new ObjectMetadata();
            // 设置输入流长度为500
            objectMetadata.setContentLength(instream.available());
            // 设置 Content type
            objectMetadata.setContentType(getcontentType(key.substring(key.lastIndexOf(".") + 1)));
            // 上传文件
            PutObjectResult putResult = cosClient.putObject(cosConfig.getBucketName(), key, instream, objectMetadata);
            etag = putResult.getETag();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (instream != null) {
                    //关闭输入流
                    instream.close();
                }
            } catch (IOException e) {
                log.error("uploadFileToCos error", e);
            }
        }
        return etag;
    }

    /**
     * Description: 判断Cos服务文件上传时文件的contentType
     *
     * @param filenameExtension 文件后缀
     * @return String
     */
    public String getcontentType(String filenameExtension) {
        String bmp = "bmp";
        if (bmp.equalsIgnoreCase(filenameExtension)) {
            return "image/bmp";
        }
        String gif = "gif";
        if (gif.equalsIgnoreCase(filenameExtension)) {
            return "image/gif";
        }
        String jpeg = "jpeg";
        String jpg = "jpg";
        String png = "png";
        if (jpeg.equalsIgnoreCase(filenameExtension) || jpg.equalsIgnoreCase(filenameExtension)
                || png.equalsIgnoreCase(filenameExtension)) {
            return "image/jpeg";
        }
        String html = "html";
        if (html.equalsIgnoreCase(filenameExtension)) {
            return "text/html";
        }
        String txt = "txt";
        if (txt.equalsIgnoreCase(filenameExtension)) {
            return "text/plain";
        }
        String vsd = "vsd";
        if (vsd.equalsIgnoreCase(filenameExtension)) {
            return "application/vnd.visio";
        }
        String pptx = "pptx";
        String ppt = "ppt";
        if (pptx.equalsIgnoreCase(filenameExtension) || ppt.equalsIgnoreCase(filenameExtension)) {
            return "application/vnd.ms-powerpoint";
        }
        String docx = ".docx";
        String doc = ".doc";
        if (docx.equalsIgnoreCase(filenameExtension) || doc.equalsIgnoreCase(filenameExtension)) {
            return "application/msword";
        }
        String xml = "xml";
        if (xml.equalsIgnoreCase(filenameExtension)) {
            return "text/xml";
        }
        String mp4 = ".mp4";
        if (mp4.equalsIgnoreCase(filenameExtension)) {
            return "application/octet-stream";
        }
        String pdf = ".pdf";
        if (pdf.equalsIgnoreCase(filenameExtension)) {
            // 使用流的形式进行上传，防止下载文件的时候访问url会预览而不是下载。  return "application/pdf";
            return "application/octet-stream";
        }
        String xls = ".xls";
        String xlsx = ".xlsx";
        if (xls.equalsIgnoreCase(filenameExtension) || xlsx.equalsIgnoreCase(filenameExtension)) {
            return "application/vnd.ms-excel";
        }
        String mp3 = ".mp3";
        if (mp3.equalsIgnoreCase(filenameExtension)) {
            return "audio/mp3";
        }
        String wav = ".wav";
        if (wav.equalsIgnoreCase(filenameExtension)) {
            return "audio/wav";
        }
        return "image/jpeg";
    }
}
